package com.zhxy.scheduler.job;

import java.util.Calendar;
import java.util.Date;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.zhxy.business.ApiUsedRecordManager;
import com.zhxy.domain.ApiUsedRecord;
import com.zhxy.util.DateRangeUtils;
import com.zhxy.util.IPUtil;
import com.zhxy.util.RedisUtils;

/**
 * 定时任务保存前一天所有API调用情况
 * 
 * @author xinyue.zheng
 */
@Component("storeApiUsedJob")
public class StoreAPIUsedJob {

    private static final Logger logger = LoggerFactory.getLogger(StoreAPIUsedJob.class);

    @Autowired
    private ApiUsedRecordManager manger;

    public void handle() {
        Date date = DateRangeUtils.yesterday();
        logger.info("Quartz Task: save api used status of " + DateRangeUtils.format(date, null));
        Calendar c = Calendar.getInstance();
        c.setTime(date); 
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        Set<String> keys = RedisUtils.getKeyByPattern(c.get(Calendar.DAY_OF_MONTH) + "_*");
        for (String key : keys) {
            String countStr = RedisUtils.get(key);
            String[] arges = key.split("_");
            String userid = arges[1];
            String index = arges[2];
            String ipLong = arges[3];
            String ip = IPUtil.longToIP(Long.valueOf(ipLong));
            ApiUsedRecord record = new ApiUsedRecord();
            record.setIp(ip);
            record.setDate(c.getTime());
            record.setUsed_count(Integer.valueOf(countStr));
            record.setUserid(userid);
            record.setApi_index(Integer.valueOf(index));
            manger.insertSelective(record);
        }
        logger.info("Quartz Task: all the records have been stored in db");
        String[] keyArr = keys.toArray(new String[0]);
        RedisUtils.delKey(keyArr);
        logger.info("Quartz Task: all the key-value have been removed in redis");
    }
}
